var tools = require("../../pros_modules/tools");
var CODE = require("../../pros_modules/restful/lib/code/CODE");
var resources = new Object(null);

resources.loadResourcesTree = function (req, res, next) {
    var root_ = {tabid: ''};
    db.models.resources.findAll({
        // where: {resType: "1"},
        order: "resSort asc"
    }).then(function (data) {
        if (data) {
            var initTree = function (root) {
                data.forEach(function (item) {
                    if (item.resParentCode === root.tabid) {
                        if (!root.childrens)root.childrens = new Array();
                        root.childrens.push(i = {
                            tabid: item.resCode,
                            icon: item.resIcon,
                            lable: item.resName,
                            href: item.resHref,
                            isClose: item.isClose,
                            initOpen: item.initOpen,
                            type: item.resType
                        });
                        initTree(i);
                    }
                });
            };
            initTree(root_);
        }
        res.restfulsuc(root_.childrens);
    })
}

//添加新的资源
resources.doAdd = function (req, res, next) {
    if (req.data)
        db.transaction({autocommit: true}, function (t) {
            return db.models.resources.create({
                resCode: req.data.resCode,
                resParentCode: req.data.resParentCode,
                resName: req.data.resName,
                resIcon: req.data.resIcon,
                resType: req.data.resType,
                resHref: req.data.resHref,
                resSort: req.data.resSort
            }, {transaction: t});
        }).then(function (t) {
            res.restfulsuc();
            console.log("doAdd successful ");
        }).catch(function (e) {
            res.restfulfai();
            console.log(e);
        });
    else
        res.restful(CODE.DATA_NULL);
}
module.exports = resources;